package com.polaris.live.popup

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.loading.LoadingUtils
import com.polaris.live.databinding.PopupPreviewCommodityBinding
import com.polaris.live.manager.DownFileManager
import com.polaris.live.resp.bean.decoration.CarAnimationLayersDto
import com.polaris.live.translation.R.string
import com.polaris.live.utils.AudioPlayProxy
import com.polaris.live.utils.DecorationUtils
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.viewscope.autoDisposeScope
import com.polaris.live.widget.PreViewEntryScreenItemView
import com.polaris.live.widget.bubble.DownLoadFileUtil
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import org.libpag.PAGImage
import org.libpag.PAGScaleMode
import org.libpag.PAGView
import java.io.File

/**
 * PreviewCommodityPopup预览商品
 * @author Created by 天晴 on 2024/7/25 15:50
 * @since 1.0.0
 **/
class PreviewCommodityPopup(
    context: Context,
    val mType: Long,
    val mUrl: String,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupPreviewCommodityBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_preview_commodity
    }

    private var isDismiss = false
    private var mPreViewEntryScreenItemView: PreViewEntryScreenItemView? = null
    override fun onCreate() {
        super.onCreate()
        mBinding = PopupPreviewCommodityBinding.bind(popupImplView)
        mBinding.closeLl.setOnSingleClickListener {
            dismiss()
        }
        if (mType == CommonConst.DressUp.LIVE_BROADCAST_ENTRY) {
            DecorationUtils.getDecorationLiveCar(mUrl)?.let { ud ->
                if (ud.soundEffect != null) {
                    DownLoadFileUtil.downPagAndAudio(null, ud.url, ud.soundEffect) { p, a ->
                        if (ud.url != p.first || ud.soundEffect != a.first) return@downPagAndAudio
                        val pag = p.second
                        val audio = a.second
                        if (pag != null && audio != null) {
                            showCarPagAndAudio(pag, a.first, ud.layers)
                        }
                    }

                } else {
                    loadPag(ud.url) {
                        showPag(it)
                    }
                }
            }
        } else if (mType == CommonConst.DressUp.LIVE_EFFECT) {
            loadPag(mUrl) {
                showPreViewEntryScreen()
            }
        } else if (mType == CommonConst.DressUp.SOUND_EFFECT) {
            val cleanUrl = mUrl.substringBefore("?")
            val lp = mBinding.pagView.layoutParams
            lp.width = 200.autoDp
            lp.height = 200.autoDp
            mBinding.pagView.layoutParams = lp
            loadPag(cleanUrl) {
                showPag(it)
            }
        } else if (mType == CommonConst.DressUp.ROOM_FRAME) {
            mBinding.pagView.visibility = View.GONE
            mBinding.ivImage.visibility = View.GONE
            mBinding.roomFrameFl.visibility = VISIBLE
            val roomCover = UserManager.getUser().coverPhoto?.roomCover
            if (roomCover != null) {
                Glide.with(context)
                    .load(ImageUtils.imgPath(roomCover))
                    .centerCrop()
                    .into(mBinding.roomBg)
            } else {
                mBinding.roomBg.setImageResource(R.drawable.default_cover)
            }
            mBinding.roomBg.visibility = View.VISIBLE
            val cleanUrl = mUrl.substringBefore("?")
            if (cleanUrl.endsWith(PagConst.PAG)) {
                loadPag(cleanUrl) {
                    mBinding.roomFramePag.visibility = View.VISIBLE
                    mBinding.roomFramePag.apply {
                        composition = PAGFile.Load(it)
                        setRepeatCount(-1)
                        if (!isPlaying) {
                            play()
                        }
                    }
                }
            } else {
                mBinding.roomFrameImg.visibility = VISIBLE
                Glide.with(context)
                    .load(ImageUtils.imgPath(cleanUrl))
                    .into(mBinding.roomFrameImg)
            }
        } else if (mUrl.endsWith(PagConst.PAG)) {
            loadPag(mUrl) {
                showPag(it)
            }
        } else {
            mBinding.ivImage.visibility = VISIBLE
            Glide.with(context)
                .load(ImageUtils.imgPath(mUrl))
                .into(mBinding.ivImage)

        }
    }

    private fun showPreViewEntryScreen() {
        mPreViewEntryScreenItemView = PreViewEntryScreenItemView(context).apply {
            setData(mUrl)
            setOnEntryScreenAnimationEnd {
                if (!isDismiss) {
                    mBinding.root.post {
                        mPreViewEntryScreenItemView?.startAnimation()
                    }
                }
            }
            layoutParams =
                ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    .apply {
                        topMargin = ScreenUtils.getScreenHeight() / 2
                    }

        }
        mBinding.root.addView(mPreViewEntryScreenItemView)
        mPreViewEntryScreenItemView?.startAnimation()
    }

    private fun showCarPagAndAudio(path: String, audio: String, layers: CarAnimationLayersDto?) {
        mBinding.pagView.visibility = View.VISIBLE
        val pagFile = PAGFile.Load(path)
        if (layers != null) {
            val user = UserManager.getUser()
            mBinding.pagView.autoDisposeScope.launch {
                val texts = layers.text
                if (texts?.isNotEmpty() == true) {
                    texts.forEach {
                        user.nickname?.let { name ->
                            val showText = if (name.length > 8) {
                                name.substring(0, 8)
                            } else {
                                name
                            }
                            val textData = pagFile.getTextData(it.index)
                            textData.text = showText
                            pagFile.replaceText(it.index, textData)
                        }

                    }
                }
                val images = layers.image
                if (images?.isNotEmpty() == true) {
                    images.forEach {
                        user.avatar?.let { avatar ->
                            val loadNetImageBitmap = ImageUtils.loadNetImageBitmap(context, avatar)
                            val pagImage = PAGImage.FromBitmap(loadNetImageBitmap)
                            pagFile.replaceImage(it.index, pagImage)

                        }

                    }
                }
            }
        }
        mBinding.pagView.apply {
            composition = pagFile
            setRepeatCount(-1)
            addListener(object : PAGView.PAGViewListener {
                override fun onAnimationStart(p0: PAGView?) {
                }

                override fun onAnimationEnd(p0: PAGView?) {
                    AudioPlayProxy.instance().recycle()
                }

                override fun onAnimationCancel(p0: PAGView?) {
                }

                override fun onAnimationRepeat(p0: PAGView?) {
                    AudioPlayProxy.instance().stopPlay()
                    AudioPlayProxy.instance().playSound()
                }

                override fun onAnimationUpdate(p0: PAGView?) {
                }

            })
            if (!isPlaying) {
                play()
            }
        }
        audio.let {
            AudioPlayProxy.instance().init(it)
            AudioPlayProxy.instance().playSound()
        }
    }

    private fun showPag(path: String) {
        mBinding.pagView.visibility = View.VISIBLE
        mBinding.pagView.apply {
            composition = PAGFile.Load(path)
            if (mType == CommonConst.DressUp.PARTY_BACKGROUND) {
                setScaleMode(PAGScaleMode.Zoom)
            }
            setRepeatCount(-1)
            if (!isPlaying) {
                play()
            }
        }
    }

    //下载
    private fun loadPag(
        pagPath: String,
        loadCallback: ((path: String) -> Unit)? = null,
    ) {

        val path =
            FileUtils.getFilePath(FileUtils.getPagFile(), pagPath)
        //如果pag已经存在代表下过了直接回调
        if (File(path).exists()) {
            loadCallback?.invoke(path)
            return
        }
        LoadingUtils.showLoadingDialog(message = string.Loading, cancelable = true)
        lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
            val loadFileCallback = DownFileManager.loadFileCallback(
                FileUtils.getPagFile(),
                pagPath
            )
            withContext(CoroutineScopeManager.mainDispatcher) {

                val loadPath = loadFileCallback?.second?.let {
                    FileUtils.getFilePath(FileUtils.getPagFile(), it)
                }
                loadPath?.let {
                    loadCallback?.invoke(loadPath)
                }
                LoadingUtils.dismissLoadingDialog()
            }
        }
    }

    override fun onDismiss() {
        AudioPlayProxy.instance().recycle()
        super.onDismiss()
        isDismiss = true
        mPreViewEntryScreenItemView?.cancelAnimation()
    }

    companion object {

        fun show(context: Context, mType: Long, mUrl: String) {
            XPopup.Builder(context)
                .isViewMode(true)
                .isDestroyOnDismiss(true)
                .hasShadowBg(false)
                .asCustom(PreviewCommodityPopup(context, mType, mUrl))
                .show()
        }
    }
}